//
//  InspectorDoneViewController.m
//  Estate
//
//  Created by wangdongdong on 16/9/5.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#define DIC_EXPANDED @"expanded" //是否是展开 0收缩 1展开
#define DIC_ARARRY @"array"
#define DIC_TITILESTRING @"title"
#define TIME @"date"
#define CELL_HEIGHT 46.0f
#import "InspectorDoneViewController.h"
#import "InspectionDoneTaskVC.h"
#import "NewInspectionTextCell.h"

@interface InspectorDoneViewController ()<UITableViewDelegate, UITableViewDataSource>

// 表格
@property (strong, nonatomic) UITableView *tableView;
// 数据
@property (strong, nonatomic) NSMutableArray *DataArray;
// 提示label(没有任务)
@property (strong, nonatomic) UILabel *taskLabel;

@end

@implementation InspectorDoneViewController

-(UITableView *)tableView{
    
    if(_tableView==nil){
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-44-49-50*BIZ)];
        [_tableView registerNib:[UINib nibWithNibName:@"NewInspectionTextCell" bundle:nil] forCellReuseIdentifier:@"detail"];
        _tableView.delegate=self;
        _tableView.dataSource=self;
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    self.tableView.tableFooterView=[[UIView alloc]initWithFrame:CGRectZero];
    self.view.backgroundColor=[UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    self.tableView.backgroundColor=[UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    [self initDataSource];
    
    if (!(self.DataArray.count > 0) && !self.taskLabel) {}
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(updateInspector) name:@"Refresh_xjrw" object:nil];
}

// 刷新数据
- (void)updateInspector {
    [self.DataArray removeAllObjects];
    [self initDataSource];
    
    if (!(self.DataArray.count > 0) && !self.taskLabel) {
    }
}

// 提示信息
- (void)noTask {
    UILabel *label = [[UILabel alloc] init];
    self.taskLabel = label;
    label.text = @"您已没有要巡检的任务了!!!";
    label.font = [UIFont systemFontOfSize:25];
    [label sizeToFit];
    
    CGPoint point;
    point.x = 375 * BIZ / 2;
    point.y = self.view.center.y - 100;
    label.center = point;
    [self.view addSubview:label];
}

// 初始化数据
- (void)initDataSource {
    // 初始化数据源
    _DataArray=[[NSMutableArray alloc] init];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    // 查找属于当前项目的巡检流程
    NSString *IPStr = [NSString stringWithFormat:@"SELECT COUNT(*), substr(INSPECT_START_TIME, 1, 4) as YEAR FROM INSPECT_PROCESS WHERE INSPECT_STATE = '5' GROUP BY YEAR ORDER BY YEAR DESC"];
    FMResultSet *IPresult = [db executeQuery:IPStr];
    
    while ([IPresult next]) {
        // 每年任务的数量
        int count = [IPresult intForColumn:@"COUNT(*)"];
        // 年
        NSString *year = [IPresult stringForColumn:@"YEAR"];
        
        // 根据年查找巡检流程
        NSString *IPStr2 = [NSString stringWithFormat:@"SELECT *, substr(INSPECT_START_TIME, 1, 4) as YEAR, substr(INSPECT_START_TIME, 6, 2) as MONTH, substr(INSPECT_START_TIME, 9, 2) as DAY FROM INSPECT_PROCESS WHERE INSPECT_STATE = '5'  AND YEAR = '%@' order by(CREATE_TIME) desc", year];
        FMResultSet *IPresult2 = [db executeQuery:IPStr2];
        
        // 二级标题数组
        NSMutableArray *secondTitleArr = [NSMutableArray array];
        while ([IPresult2 next]) {
            
            // 巡检组ID
            NSString *inspectGroupID = [IPresult2 stringForColumn:@"INSPECT_GROUP_ID"];
            // 查看当前任务是否属于当前用户
            NSString *sql = [NSString stringWithFormat:@"SELECT * FROM INSPECT_GROUP_USER WHERE INSPECT_GROUP_ID = '%@' AND INSPECT_USER_ID = '%@'", inspectGroupID, USERID];
            FMResultSet *result = [db executeQuery:sql];
            
            if ([result next]) {
                // 巡检流程ID
                NSString *inspectProcessID = [IPresult2 stringForColumn:@"ID"];
                // 巡检名称
                NSString *inspectName = [IPresult2 stringForColumn:@"INSPECT_NAME"];
                // 巡检流程创建月
                NSString *month = [IPresult2 stringForColumn:@"MONTH"];
                // 巡检流程创建日
                NSString *day = [IPresult2 stringForColumn:@"DAY"];
                // 巡检任务状态
                NSString *state = [IPresult2 stringForColumn:@"INSPECT_STATE"];
                
                // 二级标题
                NSString *secondTitle = [NSString stringWithFormat:@"%@月%@日_%@", month, day, inspectName];
                // 每条任务数据
                NSDictionary *rowDic = @{@"INSPECT_PROCES_ID":inspectProcessID, @"SECOND_TITLE":secondTitle, @"STATE":state};
                [secondTitleArr addObject:rowDic];
                
            } else {
                count --;
            }
        }
        
        // 判断当前年当前项目当前用户是否还有任务
        if (count > 0) {
            NSString *firstTitle = [NSString stringWithFormat:@"%@年 (%d条)", year, count];
            // 每组任务数据
            NSMutableDictionary *groupDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:firstTitle, DIC_TITILESTRING, secondTitleArr, DIC_ARARRY, [NSNumber numberWithInt:0], DIC_EXPANDED, nil];
            
            [self.DataArray addObject:groupDic];
        }
    }
    
    [self.tableView reloadData];
    
}



#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _DataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableDictionary *dic = [_DataArray objectAtIndex:section];
    NSArray *array = [dic objectForKey:DIC_ARARRY];
    //判断是收缩还是展开
    if ([[dic objectForKey:DIC_EXPANDED]intValue]) {
        return array.count;
    }else{
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    //判断是收缩还是展开
    NSMutableDictionary *dic=[_DataArray objectAtIndex:section];
    if ([[dic objectForKey:DIC_EXPANDED]intValue]) {
        return 10;
    }else{
        return 0;
    }
}

//控制表头分组表头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 46 * BIZ;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSMutableDictionary *dic=[self.DataArray objectAtIndex:indexPath.section];
    NSArray *array=[dic objectForKey:DIC_ARARRY];
    NSDictionary *reDic=array[indexPath.row];
    return [self cellHeightWithObj: [reDic objectForKey:@"monthTitle"]];;
}

- (CGFloat)cellHeightWithObj:(NSString *)string{
    CGFloat cellHeight = 60;
    CGFloat mWidth = [UIScreen mainScreen].bounds.size.width - 100;
    cellHeight = [string boundingRectWithSize:CGSizeMake(mWidth,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin  attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17*BIZ]} context:nil].size.height;
    if(cellHeight<=60){
        return 60;
    }else{
        return cellHeight;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    long section = indexPath.section;
    long row = indexPath.row;
    
    // 得到改组下信息
    NSMutableDictionary *dic = [self.DataArray objectAtIndex:section];
    NSArray *array = [dic objectForKey:DIC_ARARRY];
    NSDictionary *dics = array[row];
    
    NewInspectionTextCell *cell=[NewInspectionTextCell cellWithTableView:tableView];
    // 列表标题
    cell.title.text = dics[@"SECOND_TITLE"];
    cell.title.numberOfLines = 0;
    cell.textLabel.font = [UIFont systemFontOfSize:16.*BIZ];
    
    if ([dics[@"STATE"] isEqualToString:@"1"]) {
        cell.stateBottom.text = @"待巡检";
        
    } else if ([dics[@"STATE"] isEqualToString:@"2"]) {
        cell.stateBottom.text = @"待汇总";
        
    } else if ([dics[@"STATE"] isEqualToString:@"3"]) {
        cell.stateBottom.text = @"待整改";
        
    } else if ([dics[@"STATE"] isEqualToString:@"4"]) {
        cell.stateBottom.text = @"待审阅";
        
    } else if ([dics[@"STATE"] isEqualToString:@"5"]) {
        cell.stateBottom.text = @"已完成";
    }
    cell.state.text=@"";
    cell.score.text =[NSString stringWithFormat:@"总分:%d",[self getAllScoreWithTaskID:dics[@"INSPECT_PROCES_ID"]]];
    return cell;
}
//得到该任务下的所有分数
-(int)getAllScoreWithTaskID:(NSString *)taskId{
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql_1= [NSString stringWithFormat:@"select * from INSPECT_PROCESS_RECORD where INSPECT_PROCESS_ID = '%@' and inspect_item_state = '5'  and  INSPECT_USER_ID = '%@'",taskId,USERID];
    
    FMResultSet *result=[db executeQuery:sql_1];
    int score = 0;
    while ([result next]) {
        NSDictionary *dic = [result resultDictionary];
        NSLog(@"%@",dic);
        NSString *INSPECT_SCORE=[result stringForColumn:@"INSPECT_SCORE"];
        score +=[INSPECT_SCORE intValue];
    }
    [db close];
    return score;
}


//设置分组头的视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *hView = [[UIView alloc]initWithFrame:CGRectMake(0,0, DEF_SCREEN_WIDTH, CELL_HEIGHT-10)];
    hView.backgroundColor=[UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1.00];
    UIButton* eButton = [[UIButton alloc] init];
    eButton.backgroundColor=[UIColor whiteColor];
    //按钮填充整个视图
    eButton.frame = hView.frame;
    [eButton addTarget:self action:@selector(expandButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    //把节号保存到按钮tag，以便传递到expandButtonClicked方法
    eButton.tag = section;
    //根据是否展开，切换按钮显示图片
    if ([self isExpanded:section])
        [eButton setImage:  [UIImage imageNamed: @"xiala" ]forState:UIControlStateNormal];
    else
        [eButton setImage: [UIImage imageNamed: @"gengduo1" ]forState:UIControlStateNormal];
    
    //设置分组标题
    [eButton setTitle:[[_DataArray objectAtIndex:section] objectForKey:DIC_TITILESTRING]forState:UIControlStateNormal];
    
    [eButton setTitleColor:[UIColor colorWithRed:0.68 green:0.68 blue:0.68 alpha:1.00] forState:UIControlStateNormal];
    //设置字体样式
    eButton.titleLabel.font=[UIFont systemFontOfSize:14.*BIZ];
    
    //4个参数是到上边界，左边界，下边界，右边界的距离
    eButton.contentHorizontalAlignment =UIControlContentHorizontalAlignmentLeft;
    [eButton setTitleEdgeInsets:UIEdgeInsetsMake(0,5, 0,0)];
    [eButton setImageEdgeInsets:UIEdgeInsetsMake(5,DEF_SCREEN_WIDTH-30, 0,0)];
    
    //添加btn
    [hView addSubview: eButton];
    return hView;
}

#pragma mark-点击表格
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger section=indexPath.section;
    NSInteger row=indexPath.row;
    
    NSMutableDictionary *dic = [self.DataArray objectAtIndex:section];
    NSArray *array = [dic objectForKey:DIC_ARARRY];
    NSDictionary *dics = array[row];
    
    InspectionDoneTaskVC *gtasksTaskVC = [[InspectionDoneTaskVC alloc] init];
    
    gtasksTaskVC.IPID = dics[@"INSPECT_PROCES_ID"];
    [self.navigationController pushViewController:gtasksTaskVC animated:YES];
}

# pragma mark -- 内部调用
//返回指定节是否是展开的
-(int)isExpanded:(long)section{
    NSDictionary *dic = [_DataArray objectAtIndex:section];
    int expanded = [[dic objectForKey:DIC_EXPANDED] intValue];
    return expanded;
}

//按钮被点击时触发
-(void)expandButtonClicked:(id)sender {
    UIButton* btn= (UIButton*)sender;
    long section= btn.tag;//取得tag知道点击对应哪个块
    [self collapseOrExpand:section];
    //刷新tableview
    [self.tableView reloadData];
}

//对指定的节进行“展开/折叠”操作,若原来是折叠的则展开，若原来是展开的则折叠
-(void)collapseOrExpand:(long)section {
    NSMutableDictionary *dic = [_DataArray objectAtIndex:section];
    int expanded = [[dic objectForKey:DIC_EXPANDED] intValue];
    if (expanded) {
        [dic setValue:[NSNumber numberWithInt:0]forKey:DIC_EXPANDED];
    }else
    {
        [dic setValue:[NSNumber numberWithInt:1]forKey:DIC_EXPANDED];
    }
}


- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end



